package com.hospital.service.impl;

import com.hospital.entity.User;
import com.hospital.service.AuthService;
import com.hospital.service.UserService;
import com.hospital.common.UserRole;
import com.hospital.util.JwtUtil;
import com.hospital.util.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一认证服务实现类
 *
 * @author Hospital Management System
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    @Override
    public void register(User user) {
        // 检查用户名是否已存在
        User existingUser = userService.findByUsername(user.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 设置默认角色为患者
        if (user.getRole() == null) {
            user.setRole(UserRole.PATIENT);
        }
        
        // 设置默认状态为启用
        if (user.getStatus() == null) {
            user.setStatus(1);
        }
        
        // 密码加密处理
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        userService.save(user);
        log.info("用户注册成功: {}", user.getUsername());
    }

    @Override
    public Map<String, Object> login(String username, String password, Integer role) {
        // 查找用户
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 如果role参数为空，使用用户实际角色
        if (role == null) {
            role = user.getRole();
        } else {
            // 如果指定了role，验证角色是否匹配
            if (!role.equals(user.getRole())) {
                throw new RuntimeException("角色不匹配");
            }
        }
        
        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() == 0) {
            throw new RuntimeException("账号已被禁用");
        }
        
        // 生成JWT token
        String token = jwtUtil.generateToken(user.getId(), user.getUsername(), user.getRole());
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("userInfo", user);
        result.put("role", user.getRole());
        
        log.info("用户登录成功: {}, 角色: {}", username, role);
        return result;
    }

    @Override
    public User getCurrentUser() {
        // 从用户上下文中获取当前用户
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("用户未登录或登录已过期");
        }
        return currentUser;
    }

    @Override
    public void changePassword(Long userId, String oldPassword, String newPassword) {
        User user = userService.getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }
        
        // 更新新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        userService.updateById(user);
        
        log.info("用户修改密码成功: {}", user.getUsername());
    }

    @Override
    public void logout() {
        // JWT是无状态的，这里主要是清除用户上下文
        // 实际的token失效需要通过过期时间或黑名单机制实现
        UserContext.clear();
        log.info("用户退出登录");
    }
} 